<template>
  <div>
    <m-shelf title="收货地址">
      <span slot="right">
        <el-button
          class="rightAddbtn"
          size="small"
          @click="addAddrDialogVisible = true"
        >添加收货地址</el-button>
      </span>

      <div slot="content">
        <!--标题-->
        <div class="table-title">
          <span class="name">姓名</span>
          <span class="address">详细地址</span>
          <span class="tel">电话</span>
        </div>
        <div v-if="addrList.length">
          <div
            class="address-item"
            v-for="item in addrList"
            :key="item.id"
          >
            <div class="name">{{item.consignee}}</div>
            <div class="address-msg">{{item.address}}</div>
            <div class="telephone">{{item.phone}}</div>
            <div class="defalut">
              <a
                @click="changeDef(item.id)"
                href="javascript:;"
                v-text="item.is_default?'( 默认地址 )':'设为默认'"
                :class="{'defalut-address':item.is_default}"
              ></a>
            </div>
            <div class="operation">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                circle
                @click="openEditAddrDialog(item)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                circle
                @click="deleteAddr(item.id)"
              ></el-button>
            </div>
          </div>
        </div>
        <div v-else>
          <div style="padding: 80px 0;text-align: center">
            <div style="font-size: 20px">你还未添加收货地址</div>
            <div style="margin: 20px ">
              <el-button
                text="添加地址"
                @click="addAddrDialogVisible = true"
              >添加收货地址</el-button>
            </div>
          </div>
        </div>

        <el-dialog
          title="添加地址"
          :visible.sync="addAddrDialogVisible"
          width="546px"
          @close="addAddrDialogCLosed"
        >
          <el-form
            :model="addAddrForm"
            :rules="addAddrRules"
            ref="addAddrForm"
          >
            <el-form-item prop="consignee">
              <el-input
                placeholder="收货人"
                v-model.trim="addAddrForm.consignee"
              ></el-input>
            </el-form-item>
            <el-form-item prop="address">
              <el-input
                placeholder="收货地址"
                v-model.trim="addAddrForm.address"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input
                placeholder="电话号码"
                v-model.trim="addAddrForm.phone"
              ></el-input>
              <el-checkbox v-model="addAddrForm.is_default">
                设为默认
              </el-checkbox>
            </el-form-item>
          </el-form>
          <span
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="addAddrDialogVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="add()"
            >确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
          title="修改地址"
          :visible.sync="editAddrDialogVisible"
          width="546px"
          @close="editAddrDialogCLosed"
        >
          <el-form
            :model="editAddrForm"
            :rules="addAddrRules"
            ref="editAddrForm"
          >
            <el-form-item prop="consignee">
              <el-input
                placeholder="收货人"
                v-model.trim="editAddrForm.consignee"
              ></el-input>
            </el-form-item>
            <el-form-item prop="address">
              <el-input
                placeholder="收货地址"
                v-model.trim="editAddrForm.address"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input
                placeholder="电话号码"
                v-model.trim="editAddrForm.phone"
              ></el-input>
              <el-checkbox v-model="editAddrForm.is_default">
                设为默认
              </el-checkbox>
            </el-form-item>
          </el-form>
          <span
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="editAddrDialogVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="edit()"
            >确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </m-shelf>
  </div>
</template>

<script>
import MShelf from "../../../components/shelf.vue";

import { mapState, mapMutations } from "vuex";
import {
  getAddress,
  addAddress,
  deleteAddress,
  updateAddress,
  setDefaultAddress,
} from "../../../api/addr";

export default {
  name: "addressList",
  data() {
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 收获地址列表
      addrList: [],
      // 添加地址表单
      addAddrForm: {
        consignee: null,
        address: null,
        phone: null,
        is_default: false,
      },
      // 添加地址表单验证规则
      addAddrRules: {
        consignee: [
          { required: true, message: "请输入收货人", trigger: "blur" },
          {
            min: 2,
            max: 6,
            message: "长度在 2 到 6 个字符",
            trigger: ["blur", "change"],
          },
        ],
        address: [
          { required: true, message: "请输入收货地址", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 添加地址对话框的显示/隐藏
      addAddrDialogVisible: false,
      // 修改地址对话框的显示/隐藏
      editAddrDialogVisible: false,
      // 修改地址的ID
      editID: null,
      // 修改地址表单
      editAddrForm: {
        consignee: null,
        address: null,
        phone: null,
        is_default: false,
      },
    };
  },
  created() {
    this.getAddrInfo();
  },
  methods: {
    // 获取用户的收货地址
    async getAddrInfo() {
      const { data: res } = await getAddress();

      if (res.code !== 0) {
        return this.$notify.error({
          title: "警告",
          message: "收获地址获取失败",
        });
      }
      this.addrList = res.result;
      this.addrList.forEach((item, index) => {
        if (item.is_default) {
          this.addrList.splice(index, 1);
          this.addrList.unshift(item);
        }
      });
      // console.log(this.addrList)
    },
    // 监听添加地址对话框关闭事件
    addAddrDialogCLosed() {
      this.$refs.addAddrForm.resetFields();
    },
    // 添加收货地址
    async add() {
      this.$refs.addAddrForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("验证不通过");
        }

        const { data: res } = await addAddress(this.addAddrForm);

        if (res.code !== 0) {
          return this.$notify.error({
            title: "警告",
            message: "添加收货地址失败",
          });
        }

        // console.log(res)
        this.addAddrDialogVisible = false;
        this.getAddrInfo();
      });
    },
    // 删除收货地址
    async deleteAddr(id) {
      // 弹框确认用户是否删除数据
      const confirmResult = await this.$confirm(
        "确认删除该收货地址？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回字符串 confirm,取消则是 cancel
      if (confirmResult !== "confirm") {
        return;
      }

      const { data: res } = await deleteAddress(id);

      if (res.code !== 0) {
        return this.$notify.error({
          title: "警告",
          message: "删除收货地址失败",
        });
      }

      this.$notify.success({
        title: "成功",
        message: "删除收货地址成功",
      });
      this.getAddrInfo();
    },
    // 打开修改地址对话框
    openEditAddrDialog(addr) {
      this.editID = addr.id;
      this.editAddrForm = addr;
      this.editAddrDialogVisible = true;
    },
    // 监听修改地址对话框关闭事件
    editAddrDialogCLosed() {
      this.$refs.editAddrForm.resetFields();
    },
    // 修改收货地址
    edit() {
      this.$refs.editAddrForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("验证不通过");
        }

        const confirmResult = await this.$confirm(
          "确认修改该收货地址？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).catch((err) => err);

        // 如果用户确认修改，则返回字符串 confirm,取消则是 cancel
        if (confirmResult !== "confirm") {
          return;
        }

        const { data: res } = await updateAddress(
          this.editID,
          this.editAddrForm
        );

        if (res.code !== 0) {
          return this.$notify.error({
            title: "警告",
            message: "修改收货地址失败",
          });
        }
        console.log(res);
        this.$notify.success({
          title: "成功",
          message: "修改收货地址成功",
        });
        this.editAddrDialogVisible = false;
        this.getAddrInfo();
      });
    },
    // 设置默认地址
    async changeDef(id) {
      const { data: res } = await setDefaultAddress(id);

      if (res.code !== 0) {
        return this.$notify.error({
          title: "警告",
          message: "设置默认收货地址失败",
        });
      }

      this.getAddrInfo();
    },
  },
  components: {
    MShelf,
  },
};
</script>

<style lang="scss" scoped>
.table-title {
  position: relative;
  z-index: 1;
  line-height: 38px;
  height: 38px;
  padding: 0 0 0 38px;
  font-size: 12px;
  background: #eee;
  border-bottom: 1px solid #dbdbdb;
  border-bottom-color: rgba(0, 0, 0, 0.08);
  .name {
    float: left;
    text-align: left;
  }
  span {
    width: 137px;
    float: left;
    text-align: center;
    color: #838383;
  }
  .address {
    margin-left: 115px;
  }
  .tel {
    margin-left: 195px;
  }
}

.address-item {
  display: flex;
  align-items: center;
  height: 115px;
  text-align: center;
  .name {
    width: 106px;
  }
  .address-msg {
    flex: 1;
  }
  .telephone {
    width: 160px;
  }
  .defalut {
    width: 80px;
    > a {
      text-align: center;
      /*display: none;*/
    }
  }
  .operation {
    width: 135px;
    a {
      padding: 10px 5px;
    }
  }
  &:hover {
    .defalut > a {
      display: block;
    }
  }
}

.address-item + .address-item {
  border-top: 1px solid #cfcfcf;
}

.defalut-address {
  color: #626262;
  display: block;
  pointer-events: none;
  cursor: default;
}

.md {
  > div {
    text-align: left;
    margin-bottom: 15px;
    > input {
      width: 100%;
      height: 50px;
      font-size: 18px;
      padding: 10px 20px;
      border: 1px solid #ccc;
      border-radius: 6px;
      box-shadow: 0 3px 5px -4px rgba(0, 0, 0, 0.4) inset,
        -1px 0 3px -2px rgba(0, 0, 0, 0.1) inset;
      line-height: 46px;
    }
  }
}

.btn {
  margin: 0;
  width: 100%;
  height: 50px;
  font-size: 14px;
  line-height: 48px;
}
</style>